#!/usr/bin/env python3
"""
智慧农业系统 - 简化Web版本
确保基本功能正常运行
"""

from flask import Flask, render_template_string, jsonify
import random
import time
import threading
from datetime import datetime
import socket

# 创建Flask应用
app = Flask(__name__)

# 全局数据
sensor_data = {
    'timestamp': datetime.now().isoformat(),
    'soil_moisture': 45.0,
    'air_temperature': 25.0,
    'air_humidity': 60.0,
    'light_intensity': 40000.0,
    'ph_value': 6.8,
    'nitrogen': 25.0,
    'phosphorus': 15.0,
    'potassium': 30.0
}

def update_sensor_data():
    """更新传感器数据的后台任务"""
    global sensor_data
    while True:
        try:
            # 模拟数据变化
            sensor_data['soil_moisture'] += random.uniform(-1, 0.5)
            sensor_data['soil_moisture'] = max(20, min(80, sensor_data['soil_moisture']))
            
            sensor_data['air_temperature'] += random.uniform(-0.5, 0.5)
            sensor_data['air_temperature'] = max(15, min(35, sensor_data['air_temperature']))
            
            sensor_data['air_humidity'] += random.uniform(-2, 2)
            sensor_data['air_humidity'] = max(40, min(90, sensor_data['air_humidity']))
            
            sensor_data['light_intensity'] += random.uniform(-2000, 2000)
            sensor_data['light_intensity'] = max(10000, min(70000, sensor_data['light_intensity']))
            
            sensor_data['ph_value'] += random.uniform(-0.02, 0.02)
            sensor_data['ph_value'] = max(6.0, min(8.0, sensor_data['ph_value']))
            
            sensor_data['nitrogen'] += random.uniform(-0.1, 0.05)
            sensor_data['nitrogen'] = max(10, min(50, sensor_data['nitrogen']))
            
            sensor_data['phosphorus'] += random.uniform(-0.1, 0.05)
            sensor_data['phosphorus'] = max(5, min(30, sensor_data['phosphorus']))
            
            sensor_data['potassium'] += random.uniform(-0.1, 0.05)
            sensor_data['potassium'] = max(15, min(45, sensor_data['potassium']))
            
            sensor_data['timestamp'] = datetime.now().isoformat()
            
            time.sleep(3)
        except Exception as e:
            print(f"数据更新错误: {e}")
            time.sleep(5)

def find_available_port(start_port=8080):
    """找到可用端口"""
    for port in range(start_port, start_port + 20):
        try:
            with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
                s.bind(('', port))
                return port
        except OSError:
            continue
    return 8080

# HTML模板
HTML_TEMPLATE = """
<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>🌱 智慧农业边缘控制系统</title>
    <style>
        body {
            font-family: Arial, sans-serif;
            margin: 0;
            padding: 20px;
            background: linear-gradient(135deg, #e8f5e8 0%, #f0f8ff 100%);
            min-height: 100vh;
        }
        .container {
            max-width: 1200px;
            margin: 0 auto;
            background: white;
            border-radius: 15px;
            box-shadow: 0 8px 25px rgba(0,0,0,0.1);
            overflow: hidden;
        }
        .header {
            background: linear-gradient(135deg, #4CAF50 0%, #45a049 100%);
            color: white;
            padding: 30px 20px;
            text-align: center;
        }
        .header h1 {
            margin: 0;
            font-size: 2.5em;
            text-shadow: 2px 2px 4px rgba(0,0,0,0.3);
        }
        .header p {
            margin: 10px 0 0 0;
            opacity: 0.9;
            font-size: 1.1em;
        }
        .status-bar {
            background: #f8f9fa;
            padding: 15px 30px;
            display: flex;
            justify-content: space-between;
            align-items: center;
            border-bottom: 1px solid #dee2e6;
        }
        .status-item {
            display: flex;
            align-items: center;
            gap: 8px;
        }
        .status-indicator {
            width: 12px;
            height: 12px;
            border-radius: 50%;
            background: #4CAF50;
            animation: pulse 2s infinite;
        }
        @keyframes pulse {
            0% { opacity: 1; }
            50% { opacity: 0.5; }
            100% { opacity: 1; }
        }
        .dashboard {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(300px, 1fr));
            gap: 25px;
            padding: 30px;
        }
        .card {
            background: #f8f9fa;
            border-radius: 15px;
            padding: 25px;
            border-left: 4px solid #4CAF50;
            box-shadow: 0 4px 15px rgba(0,0,0,0.1);
            transition: transform 0.3s ease;
        }
        .card:hover {
            transform: translateY(-5px);
        }
        .card h3 {
            margin: 0 0 20px 0;
            color: #2e7d32;
            font-size: 1.4em;
            display: flex;
            align-items: center;
            gap: 10px;
        }
        .sensor-grid {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(140px, 1fr));
            gap: 15px;
        }
        .sensor-item {
            background: white;
            padding: 15px;
            border-radius: 10px;
            text-align: center;
            box-shadow: 0 2px 8px rgba(0,0,0,0.1);
            transition: all 0.3s ease;
        }
        .sensor-item:hover {
            transform: scale(1.05);
            box-shadow: 0 4px 15px rgba(0,0,0,0.2);
        }
        .sensor-value {
            font-size: 1.8em;
            font-weight: bold;
            color: #2e7d32;
            margin-bottom: 5px;
        }
        .sensor-label {
            color: #666;
            font-size: 0.9em;
            font-weight: 500;
        }
        .control-section {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
            gap: 15px;
        }
        .control-item {
            background: white;
            padding: 20px;
            border-radius: 10px;
            text-align: center;
            box-shadow: 0 2px 8px rgba(0,0,0,0.1);
        }
        .btn {
            background: #4CAF50;
            color: white;
            border: none;
            padding: 12px 24px;
            border-radius: 25px;
            cursor: pointer;
            font-size: 1em;
            font-weight: 500;
            transition: all 0.3s ease;
            margin: 5px;
        }
        .btn:hover {
            background: #45a049;
            transform: translateY(-2px);
            box-shadow: 0 5px 15px rgba(76, 175, 80, 0.4);
        }
        .btn-secondary {
            background: #2196F3;
        }
        .btn-secondary:hover {
            background: #1976D2;
        }
        .btn-warning {
            background: #FF9800;
        }
        .btn-warning:hover {
            background: #F57C00;
        }
        .info-section {
            background: white;
            padding: 20px;
            border-radius: 10px;
            box-shadow: 0 2px 8px rgba(0,0,0,0.1);
        }
        .footer {
            text-align: center;
            padding: 20px;
            background: #f8f9fa;
            color: #666;
            border-top: 1px solid #dee2e6;
        }
        @media (max-width: 768px) {
            .dashboard {
                grid-template-columns: 1fr;
                padding: 15px;
            }
            .header h1 {
                font-size: 2em;
            }
            .status-bar {
                flex-direction: column;
                gap: 10px;
            }
        }
    </style>
</head>
<body>
    <div class="container">
        <!-- 头部 -->
        <div class="header">
            <h1>🌱 智慧农业边缘控制系统</h1>
            <p>Smart Agriculture Edge Control System</p>
        </div>
        
        <!-- 状态栏 -->
        <div class="status-bar">
            <div class="status-item">
                <div class="status-indicator"></div>
                <span>系统运行正常</span>
            </div>
            <div class="status-item">
                <span>📡 传感器: 9/9 在线</span>
            </div>
            <div class="status-item">
                <span>🕒 最后更新: <span id="last-update">--</span></span>
            </div>
        </div>
        
        <!-- 主仪表板 -->
        <div class="dashboard">
            <!-- 传感器数据 -->
            <div class="card">
                <h3>📊 环境监控</h3>
                <div class="sensor-grid" id="sensor-display">
                    <!-- 传感器数据将在这里动态加载 -->
                </div>
                <div style="margin-top: 20px; text-align: center;">
                    <button class="btn btn-secondary" onclick="refreshData()">🔄 刷新数据</button>
                </div>
            </div>
            
            <!-- 灌溉控制 -->
            <div class="card">
                <h3>💧 灌溉控制</h3>
                <div class="control-section">
                    <div class="control-item">
                        <h4>区域 A</h4>
                        <p>土壤湿度: <span id="zone-a-moisture">--</span>%</p>
                        <button class="btn" onclick="toggleIrrigation('A')">💧 启动灌溉</button>
                    </div>
                    <div class="control-item">
                        <h4>区域 B</h4>
                        <p>土壤湿度: <span id="zone-b-moisture">--</span>%</p>
                        <button class="btn" onclick="toggleIrrigation('B')">💧 启动灌溉</button>
                    </div>
                </div>
            </div>
            
            <!-- AI分析 -->
            <div class="card">
                <h3>🤖 AI智能分析</h3>
                <div class="info-section">
                    <button class="btn btn-warning" onclick="runAI()">🔍 执行AI检测</button>
                    <div id="ai-result" style="margin-top: 15px; padding: 15px; background: #f0f0f0; border-radius: 8px;">
                        <p>点击按钮开始AI分析...</p>
                    </div>
                </div>
            </div>
            
            <!-- 系统状态 -->
            <div class="card">
                <h3>⚙️ 系统状态</h3>
                <div class="info-section">
                    <div style="display: grid; gap: 10px;">
                        <div style="display: flex; justify-content: space-between;">
                            <span>传感器状态:</span>
                            <span style="color: #4CAF50; font-weight: bold;">✅ 正常</span>
                        </div>
                        <div style="display: flex; justify-content: space-between;">
                            <span>数据库连接:</span>
                            <span style="color: #4CAF50; font-weight: bold;">✅ 已连接</span>
                        </div>
                        <div style="display: flex; justify-content: space-between;">
                            <span>网络状态:</span>
                            <span style="color: #4CAF50; font-weight: bold;">✅ 在线</span>
                        </div>
                        <div style="display: flex; justify-content: space-between;">
                            <span>AI模型:</span>
                            <span style="color: #4CAF50; font-weight: bold;">✅ 就绪</span>
                        </div>
                    </div>
                    <div style="margin-top: 15px; text-align: center;">
                        <button class="btn btn-secondary" onclick="exportData()">📊 导出数据</button>
                    </div>
                </div>
            </div>
        </div>
        
        <!-- 底部 -->
        <div class="footer">
            <p>🌱 智慧农业边缘控制系统 | 数据每3秒自动更新 | 技术支持: 智慧农业团队</p>
        </div>
    </div>

    <script>
        let updateInterval;
        
        // 传感器配置
        const sensors = {
            'soil_moisture': { name: '土壤湿度', unit: '%', icon: '🌱' },
            'air_temperature': { name: '空气温度', unit: '°C', icon: '🌡️' },
            'air_humidity': { name: '空气湿度', unit: '%', icon: '💧' },
            'light_intensity': { name: '光照强度', unit: 'lux', icon: '☀️' },
            'ph_value': { name: 'pH值', unit: '', icon: '⚗️' },
            'nitrogen': { name: '氮含量', unit: 'ppm', icon: '🧪' },
            'phosphorus': { name: '磷含量', unit: 'ppm', icon: '🔬' },
            'potassium': { name: '钾含量', unit: 'ppm', icon: '⚡' }
        };
        
        // 初始化
        document.addEventListener('DOMContentLoaded', function() {
            updateSensorData();
            startAutoUpdate();
        });
        
        // 启动自动更新
        function startAutoUpdate() {
            updateInterval = setInterval(updateSensorData, 3000);
        }
        
        // 更新传感器数据
        function updateSensorData() {
            fetch('/api/sensors')
                .then(response => response.json())
                .then(data => {
                    const container = document.getElementById('sensor-display');
                    container.innerHTML = '';
                    
                    Object.entries(sensors).forEach(([key, config]) => {
                        if (data[key] !== undefined) {
                            const value = typeof data[key] === 'number' ? data[key].toFixed(1) : data[key];
                            
                            const sensorItem = document.createElement('div');
                            sensorItem.className = 'sensor-item';
                            sensorItem.innerHTML = `
                                <div style="font-size: 1.5em; margin-bottom: 8px;">${config.icon}</div>
                                <div class="sensor-value">${value}</div>
                                <div class="sensor-label">${config.name} ${config.unit}</div>
                            `;
                            container.appendChild(sensorItem);
                        }
                    });
                    
                    // 更新区域湿度显示
                    document.getElementById('zone-a-moisture').textContent = data.soil_moisture.toFixed(1);
                    document.getElementById('zone-b-moisture').textContent = (data.soil_moisture + random(-5, 5)).toFixed(1);
                    
                    // 更新最后更新时间
                    document.getElementById('last-update').textContent = new Date().toLocaleTimeString();
                })
                .catch(error => {
                    console.error('数据更新失败:', error);
                    showNotification('数据更新失败', 'error');
                });
        }
        
        // 随机数生成
        function random(min, max) {
            return Math.random() * (max - min) + min;
        }
        
        // 刷新数据
        function refreshData() {
            updateSensorData();
            showNotification('数据已刷新', 'success');
        }
        
        // 切换灌溉
        function toggleIrrigation(zone) {
            showNotification(`区域 ${zone} 灌溉系统已启动`, 'success');
        }
        
        // 运行AI分析
        function runAI() {
            const resultDiv = document.getElementById('ai-result');
            resultDiv.innerHTML = '<p style="color: #FF9800;">🔄 AI分析中...</p>';
            
            setTimeout(() => {
                const results = [
                    '✅ 分析完成！',
                    '🌱 环境状态: 良好',
                    '💧 建议保持当前灌溉频率',
                    '🐛 未检测到病虫害风险',
                    '📊 综合评分: 85/100'
                ];
                
                resultDiv.innerHTML = results.map(r => `<p style="margin: 5px 0;">${r}</p>`).join('');
                showNotification('AI分析完成', 'success');
            }, 2000);
        }
        
        // 导出数据
        function exportData() {
            fetch('/api/sensors')
                .then(response => response.json())
                .then(data => {
                    const exportData = {
                        timestamp: new Date().toISOString(),
                        sensor_data: data,
                        export_type: 'current_data'
                    };
                    
                    const blob = new Blob([JSON.stringify(exportData, null, 2)], {type: 'application/json'});
                    const url = URL.createObjectURL(blob);
                    const a = document.createElement('a');
                    a.href = url;
                    a.download = `智慧农业数据_${new Date().toISOString().slice(0,10)}.json`;
                    a.click();
                    URL.revokeObjectURL(url);
                    
                    showNotification('数据导出成功', 'success');
                });
        }
        
        // 显示通知
        function showNotification(message, type = 'info') {
            const notification = document.createElement('div');
            notification.style.cssText = `
                position: fixed;
                top: 20px;
                right: 20px;
                background: ${type === 'success' ? '#4CAF50' : type === 'error' ? '#f44336' : '#2196F3'};
                color: white;
                padding: 15px 20px;
                border-radius: 8px;
                box-shadow: 0 4px 20px rgba(0,0,0,0.3);
                z-index: 1000;
                font-weight: 500;
            `;
            notification.textContent = message;
            
            document.body.appendChild(notification);
            
            setTimeout(() => {
                document.body.removeChild(notification);
            }, 3000);
        }
        
        // 页面离开时清理
        window.addEventListener('beforeunload', () => {
            if (updateInterval) {
                clearInterval(updateInterval);
            }
        });
    </script>
</body>
</html>
"""

@app.route('/')
def index():
    return render_template_string(HTML_TEMPLATE)

@app.route('/api/sensors')
def get_sensors():
    return jsonify(sensor_data)

@app.route('/api/status')
def get_status():
    return jsonify({
        'status': 'online',
        'timestamp': datetime.now().isoformat(),
        'sensors_active': True,
        'message': '系统运行正常'
    })

def main():
    """主函数"""
    # 启动传感器数据更新线程
    sensor_thread = threading.Thread(target=update_sensor_data, daemon=True)
    sensor_thread.start()
    
    # 找到可用端口
    port = find_available_port()
    
    print("🌱 智慧农业系统启动")
    print("=" * 40)
    print(f"📡 传感器模拟器: 已启动")
    print(f"🌐 Web服务器端口: {port}")
    print(f"🔗 访问地址: http://localhost:{port}")
    print(f"📱 移动端访问: http://192.168.x.x:{port}")
    print("🔧 按 Ctrl+C 停止服务")
    print("=" * 40)
    
    try:
        app.run(host='0.0.0.0', port=port, debug=False, threaded=True)
    except KeyboardInterrupt:
        print("\n🛑 系统已停止")

if __name__ == "__main__":
    main()